/*
 *    Copyright 2022 The DSMS Authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.dsms.common.remotecall.service.impl;


import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.dsms.common.constant.ResultCode;
import com.dsms.common.exception.DsmsEngineException;
import com.dsms.common.remotecall.model.RemoteRequest;
import com.dsms.common.remotecall.model.RemoteResponse;
import com.dsms.common.remotecall.service.IRemoteCall;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;


@Slf4j
@Service
public class RemoteCallImpl implements IRemoteCall {

    public static final int MAX_RETRIES = 3;

    private final RestTemplateBuilder restTemplateBuilder;
    @Autowired
    public RemoteCallImpl (RestTemplateBuilder restTemplateBuilder) {
        this.restTemplateBuilder = restTemplateBuilder;
    }

    @Override
    public RemoteResponse callRestfulApi(RemoteRequest remoteRequest) throws Throwable {
        RemoteResponse remoteResponse = new RemoteResponse();
        HttpRequest httpRequest = null;

        UrlBuilder of = UrlBuilder.of(remoteRequest.getRemoteFixedParam().getScheme(), remoteRequest.getRemoteFixedParam().getHost(), remoteRequest.getRemoteFixedParam().getPort(), remoteRequest.getUrlPrefix(), null, null, StandardCharsets.UTF_8);
        String url = of.build();
        switch (remoteRequest.getHttpMethod()) {
            case GET:
                httpRequest = HttpUtil.createRequest(Method.GET, url);
                break;
            case POST:
                httpRequest = HttpUtil.createRequest(Method.POST, url);
                break;
            default:
                log.error("unknown request method");
                throw new RuntimeException("unknown request method");
        }
        httpRequest.timeout(3000);
        httpRequest.basicAuth(remoteRequest.getRemoteFixedParam().getUsername(), remoteRequest.getRemoteFixedParam().getPassword());
        if (remoteRequest.getRequestBody() != null) {
            httpRequest.body(remoteRequest.getRequestBody());
        }
        int numAttempts = 0;
        HttpResponse httpResponse = null;
        do {
            numAttempts++;
            try {
                httpResponse = httpRequest.execute();
                if (httpResponse != null) {
                    break;
                }
            } catch (IORuntimeException ex) {
                log.error("remotecall fail! fail time:{},fail reason:{}", numAttempts, ex.getMessage(), ex);
            }
            TimeUnit.MILLISECONDS.sleep(numAttempts * 100l);
        } while (numAttempts <= MAX_RETRIES);
        if (null == httpResponse) {
            throw new DsmsEngineException(ResultCode.REMOTE_CALL_FAIL);
        }
        if (httpResponse.getStatus() == HttpStatus.UNAUTHORIZED.value()) {
            throw new AuthenticationServiceException("auth: Incorrect password");
        }
        log.debug("request:{},response:{}", remoteRequest, httpResponse);
        remoteResponse.setBody(httpResponse.body());

        return remoteResponse;
    }

    @Override
    public RemoteResponse callLibApi(RemoteRequest remoteRequest) {
        return null;
    }
}
